// pages/study/study.js
import { server } from '../../config/server';
import { focuscard } from '../../server/focuscard';

Page({

    /**
     * 页面的初始数据
     */
    data: {
        server_addr: "",
        clock: {
            remainTime: 0,      // 剩余倒计时秒数
            minutes: 15,
            seconds: 0,
            isRunning: false,   // 是否正在倒计时
            intervalId: null,   // 倒计时的定时器ID
            isStart: false,     // 是否开始倒计时
            formatMinutes: "15",  // 显示的分钟数
            formatSeconds: "00",  // 显示的秒数
        },
        durationList: [
            {
                id: 1,
                text: '15分钟',
                value: 15,
                active: true
            }, {
                id: 2,
                text: '30分钟',
                value: 30,
                active: false
            }, {
                id: 3,
                text: '45分钟',
                value: 45,
                active: false
            }, {
                id: 4,
                text: '60分钟',
                value: 60,
                active: false
            }
        ],
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // 加载服务器地址
        this.setData({
            server_addr: server.server_addr
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        this.resetClock();
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    /*
     * 跳转到 专注记录 页面
     */
    toCheckInCalendar() {
        wx.navigateTo({
            url: '/pages/checkInCalendar/checkInCalendar',
        });
    },

    /*
     * 开始暂停按钮
     */
    startClock() {
        let clock = this.data.clock;
        if (clock.isStart) {
            if (clock.isRunning) {
                clock.isRunning = false;
            } else {
                clock.isRunning = true;
            }
        } else {
            // 开始倒计时的状态变量
            clock.isStart = true;
            clock.isRunning = true;
            // 设置倒计时时间
            this.resetClockTime();
            // 设置倒计时的定时器
            clock.intervalId = setInterval(() => {
                let clock = this.data.clock;
                console.log('interval');
                if (clock.isRunning) {
                    clock.remainTime--;
                    // 更新倒计时显示
                    clock.minutes = Math.floor(clock.remainTime / 60);
                    clock.seconds = clock.remainTime % 60;
                    if (clock.remainTime <= 0) {
                        // 倒计时结束，重置状态
                        clock.isRunning = false;
                        clock.isStart = false;
                        // 关闭定时器
                        clearInterval(clock.intervalId);
                        // 保存到专注记录中
                        this.focusCheckIn().then((res) => {
                            console.log('打卡成功', res);
                        });
                    }
                }
                this.setData({ clock });
                this.fotmatClockShowNum();
            }, 1000);
        }
        // 更新时钟
        this.setData({ clock });
        this.fotmatClockShowNum();
    },

    /*
     * 重置时钟状态
     */
    resetClock() {
        let clock = this.data.clock;
        // 开始倒计时的状态变量
        clock.isStart = false;
        clock.isRunning = false;
        // 设置倒计时的定时器
        if (clock.intervalId) {
            clearInterval(clock.intervalId);
            clock.intervalId = null;
        }
        this.setData({ clock });
        // 重置倒计时显示的时间
        this.resetClockTime();
        this.fotmatClockShowNum();
    },

    /*
     * 选择专注时长
     */
    selectDuration(e) {
        let durationItem = e.currentTarget.dataset.item;
        let durationList = this.data.durationList;
        let clock = this.data.clock;
        // 调用重置函数
        this.resetClock();
        // 正常的逻辑
        for (let i = 0; i < durationList.length; i++) {
            let item = durationList[i];
            let itemId = durationItem.id;
            if (itemId == item.id) {
                // 设置选中样式
                durationList[i].active = true;
                // 刷新时钟状态
                clock.minutes = durationItem.value;
                clock.seconds = 0;
                clock.isRunning = false;
                clock.isStart = false;
                if (clock.intervalId) {
                    clearInterval(clock.intervalId);
                    clock.intervalId = null;
                }
            } else {
                durationList[i].active = false;
            }
        }
        this.setData({
            clock,
            durationList
        });
        this.fotmatClockShowNum();
    },

    /*
     * 重置倒计时时间
     */
    resetClockTime() {
        let clock = this.data.clock;
        let durationList = this.data.durationList;
        // 重置倒计时显示的时间
        for (let i = 0; i < durationList.length; i++) {
            let item = durationList[i];
            if (item.active) {
                clock.minutes = item.value;
                clock.seconds = 0;
            }
        }
        // 设置倒计时时间
        clock.remainTime = clock.minutes * 60 + clock.seconds;
        this.setData({
            clock,
            durationList
        });
        this.fotmatClockShowNum();
    },

    async focusCheckIn() {
        try {
            let durationList = this.data.durationList;
            let duration = 15;
            for (let i = 0; i < durationList.length; i++) {
                let item = durationList[i];
                if (item.active) {
                    duration = item.value;
                    break;
                }
            }
            let res = await focuscard.focuscard(duration);
            if (res.success) {
                uni.showToast({
                    title: '专注模式结束，休息一下吧！',
                    icon: 'none'
                });
            } else {
                uni.showToast({
                    title: '专注模式结束，休息一下吧！',
                    icon: 'none'
                })
            }
        } catch (err) {
            uni.showToast({
                title: '网络错误！！！',
                icon: 'none'
            });
        }
    },

    /*
     * 格式化时钟的显示
     */
    fotmatClockShowNum() {
        let clock = this.data.clock;
        clock.formatMinutes = this.formatNum(clock.minutes);
		clock.formatSeconds = this.formatNum(clock.seconds);
        this.setData({ clock });
    },

    /*
     * 数字补全到两位的函数
     */
    formatNum(n) {
        if (n < 10) {
            return '0' + n;
        } else {
            return n;
        }
    }
})